package com.rizzo.back.helper;

import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.spell.LuceneDictionary;
import org.apache.lucene.search.spell.SpellChecker;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.SearchFactory;
import org.hibernate.search.store.DirectoryProvider;

import java.io.File;
import java.io.IOException;

/**
 * TODO Insert JavaDoc!
 */
public class SpellcheckHelper {

    private String hibernateSearchBaseDir;

    /**
     * TODO 
     * @param clazz
     * @param fieldName
     * @param session
     * @return
     * @throws IOException
     */
    public SpellChecker getSpellChecker(Class clazz, String fieldName, FullTextSession session) throws IOException {
        SearchFactory searchFactory = session.getSearchFactory();
        DirectoryProvider[] providers = searchFactory.getDirectoryProviders(clazz);
        Directory directory = providers[0].getDirectory();
        IndexReader spellReader = null;
        SpellChecker spellchecker = null;
        try {
            // read from the clazz directory
            spellReader = IndexReader.open(directory);
            LuceneDictionary dictionary = new LuceneDictionary(IndexReader.open(directory), fieldName);
            // build the spellcheck index in the base directory
            FSDirectory spellDir = FSDirectory.getDirectory(this.hibernateSearchBaseDir + System.getProperty("file.separator") + clazz.getName() + "-spellcheck");
            spellchecker = new SpellChecker(spellDir);
            // build the directory if it does not exist
            final File indexDirectory = new File(this.hibernateSearchBaseDir + System.getProperty("file.separator") + clazz.getName() + "-spellcheck");
            if (!(indexDirectory.exists() && indexDirectory.listFiles().length > 2)) {
                spellchecker.indexDictionary(dictionary);
            }
        } finally {
            if (spellReader != null) {
                spellReader.close();
            }
        }
        return spellchecker;
    }

    public void setHibernateSearchBaseDir(String hibernateSearchBaseDir) {
        this.hibernateSearchBaseDir = hibernateSearchBaseDir;
    }
}
